package gormx

import (
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

var db *gorm.DB

func GetGormDB() *gorm.DB {
	return db
}

type MysqlConfig struct {
	DataSourceName  string `yaml:"dataSourceName"`
	MaxIdleCons     int    `yaml:"maxIdleCons"`
	MaxOpenCons     int    `yaml:"maxOpenCons"`
	ConnMaxLifetime int    `yaml:"connMaxLifetime"`
	Debug           bool   `yaml:"debug"`
}

func OpenGormDB() (err error) {
	c, err := loadMysqlConfig("mysql")
	if err != nil {
		return err
	}

	db0, err := gorm.Open(mysql.Open(c.DataSourceName), &gorm.Config{
		AllowGlobalUpdate: false,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 使用单数表名
		},
	})
	if err != nil {
		return err
	}
	sqlDB, err := db0.DB()
	if err != nil {
		return err
	}
	sqlDB.SetMaxIdleConns(c.MaxIdleCons)
	sqlDB.SetMaxOpenConns(c.MaxOpenCons)
	sqlDB.SetConnMaxLifetime(time.Duration(c.ConnMaxLifetime) * time.Second)
	if c.Debug {
		db0 = db0.Debug()
	}
	db = db0

	return nil
}
